<template>
	<view class="content">
		<view class='condition' v-if='settled == ""'>
			<text class='month' @click='showCalender = true'>{{month}}</text>
			<text style='color:coral;padding-left:5px'>[￥{{ amount }}]</text>
		</view>
		<u-datetime-picker :show="showCalender" v-model="startDateTime" mode="year-month" @confirm='chooseMonth'
			@close='showCalender = false' @cancel='showCalender = false'></u-datetime-picker>
		<!-- <u-popup :show="show" @close="show=false" mode='top'>
			<view style='padding:10px'>
				<view style='display: flex;flex-wrap: wrap;'>
					<view v-for='(item,index) in types' style='padding:5px 10px;' :key='index'>
						<u-tag v-if='choosedTypes.indexOf(index) == -1' :text="item" plain size="large"
							@click='chooseType(index)' type="primary"></u-tag>
						<u-tag v-else :text="item" size="large" type="primary" @click='delType(index)'></u-tag>
					</view>
				</view>
				<view style='padding-top:10px'>
					<u-button text='确定' type='error' @click='findData'></u-button>
				</view>
			</view>
		</u-popup> -->
		<view>
			<view v-if='settled == ""' style='padding-top:50px;'></view>
			<view v-for='(day,index) in dateList' :key='index'>
				<view v-if='day.amount > 0' style='color:#909399;padding:10px;font-size:14px;background-color: #f3f3f3;margin-top:5px;'>
					<u-row @click='getOrderList(index)'>
						<u-col span='6'>
							<view>{{day.date}}</view>
						</u-col>
						<u-col span='5' @click='changeShow(index)'>
							<view style='text-align: right;padding-right:10px'>
								合计:￥{{day.amount}}元
							</view>
						</u-col>
						<u-col span='1' @click='changeShow(index)'>
							<view v-if='day.show'>
								<u-icon name="arrow-up" color='#909399'></u-icon>
							</view>
							<view v-else>
								<u-icon name="arrow-down" color='#909399'></u-icon>
							</view>
						</u-col>
					</u-row>
				</view>
				<u-line></u-line>
				<view v-if='day.show == true && day.orderList && day.orderList.length > 0'>
					<view v-for='order in day.orderList'>
						<view class='order-list'>
							<view style='padding:10px;color:#909399'>
								<view style='padding-bottom:10px;'>
									下单人:{{order.user.profile.__toString}}
								</view>
								<view>金额:￥{{order.amount}}</view>
							</view>
							<view>
								<u-row>
									<!-- <u-col span='6'>
										<view style='padding:5px;'>
											<u-button type='info' shape='circle' text='查看订单'
												@click='toUrl(`/pages/mine/order-detail?id=${order.orderId}`)'></u-button>
										</view>
									</u-col> -->
									<u-col span='12'>
										<view style='padding:5px;'>
											<u-button type='success' shape='circle' text='查看明细'
												@click='getSettleDetail(order.orderId)'></u-button>
										</view>
									</u-col>
								</u-row>
							</view>
						</view>
					</view>
				</view>
			</view>
			<u-popup :show="showItems" @close="showItems = false" mode='bottom'>
				<view style='padding:10px;max-height: 70vh;overflow: auto;'>
					<u-row>
						<u-col span='4'>
							<view class='list'>
								销售产品
							</view>
						</u-col>
						<u-col span='4'>
							<view class='list'>
								佣金类型
							</view>
						</u-col>
						<u-col span='4'>
							<view class='list'>
								佣金
							</view>
						</u-col>
					</u-row>
					<u-line></u-line>
					<view v-for='item in orderSettleItems'>
						<u-row>
							<u-col span='4'>
								<view class='list' style='text-align: left;'>
									{{item.specification}}
								</view>
							</u-col>
							<u-col span='4'>
								<view class='list'>
									{{item.profitType ? item.profitType.name : '销售佣金'}}
								</view>
							</u-col>
							<u-col span='4'>
								<view class='list'>
									￥{{item.amount}}
									<view>
										<text v-if='item.settled' style='font-size:10px;color:#19be6b'>已到账</text>
										<text v-else style='font-size:10px;color:#ff9900'>未到账</text>
									</view>
								</view>
							</u-col>
						</u-row>
						<u-line></u-line>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				type: 0,
				dateList: [],
				month: '',
				choosedTypes: ['-1'],
				showCalender: false,
				yearMonth: '',
				show: false,
				nextMonth: '',
				amount: 0,
				startDate: '',
				endDate: '',
				startDateTime: '',
				storeId: 0,
				settled: '',
				orderSettleItems: [],
				showItems: false
			}
		},
		onLoad(options) {
			// if (typeof(options.settled) != 'undefined') {
			// 	// 有传的，是查看未分账的
			// 	this.settled = 1
			// 	this.getSettleItems()
			// } else {
			// 	if (typeof(options.type) != 'undefined') {
			// 		this.type = options.type
			// 	}
				let date = new Date()
				this.startDate = `${date.getFullYear()}/${date.getMonth() + 1}/01`
				this.endDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
				this.month = `${date.getFullYear()}年${date.getMonth() + 1}月`
				this.startDateTime = date.getTime()
				this.getSettleItems()
			// }
		},
		methods: {
			changeShow(index) {
				if(this.dateList[index].show == false){
					this.dateList[index].show = true
				}else{
					this.dateList[index].show = false
				}
				// this.dateList[index].show = !this.dateList[index].show
			},
			toOrderDetail(item) {
				if (item.settle.__metadata.orderItem) {
					uni.navigateTo({
						url: `/pages/orders/order-detail?id=${item.settle.__metadata.orderItem.__metadata.order.id}`
					})
				}
			},
			chooseMonth(e) {
				let date = new Date(e.value)
				const nextDate = new Date(date.getTime() + 86400000)
				this.startDateTime = date.getTime()
				let year = date.getFullYear()
				let month = date.getMonth() + 1
				let lastDay = new Date(year, month, 0).getDate();
				this.month = `${year}年${month}月`
				this.startDate = `${year}/${month}/01`
				this.endDate = `${year}/${month}/${lastDay}`
				this.showCalender = false
				this.logs = []
				this.dateList = [],
					this.dateListArray = []
				this.page = 1
				this.status = 'loadmore'
				this.getSettleItems()
			},

			getSettleItems() {
				uni.showLoading()
				let startTime = (new Date(this.startDate)).getTime()
				let endTime = (new Date(this.endDate)).getTime()
				console.log(this.startDate, this.endDate, startTime, endTime)
				let settleItems = []
				for (let i = startTime; i <= endTime; i += 86400000) {
					let theDate = new Date(i)
					theDate = `${theDate.getFullYear()}/${theDate.getMonth() + 1}/${theDate.getDate()}`
					settleItems.push({
						date: theDate,
						amount: 0,
						show: false,
						orderList: []
					})
				}
				console.log(settleItems)
				let promise = []
				let totalAmount = 0
				for (let i of settleItems) {
					promise.push(
						this.request.get(`api/settle-items`, {
							'@filter': `entity.getCreatedTime() >= datetime.get('${i.date} 00:00:00') && entity.getCreatedTime() <= datetime.get('${i.date} 23:59:59')`,
							'@select': `SUM(entity.amount) as amount`
						}).then((res) => {
							if (res.data.length > 0 && res.data[0].amount) {
								console.log(res.data)
								i.amount = res.data[0].amount
								totalAmount += parseFloat(res.data[0].amount)
							}
						})
					)
				}
				Promise.all(promise).then((res) => {
					this.dateList = settleItems
					this.amount = totalAmount.toFixed(2)
					uni.hideLoading()
				})
			},
			// 根据日期，按订单统计
			getOrderList(index) {
				let date = this.dateList[index].date
				console.log(date)
				if (this.dateList[index].amount > 0) {
					if (this.dateList[index].orderList.length == 0) {
						uni.showLoading()
						this.request.get(`api/settle-items`, {
							'@filter': `entity.getCreatedTime() >= datetime.get('${date} 00:00:00') && entity.getCreatedTime() <= datetime.get('${date} 23:59:59')`,
							'@display': {
								amount: 'entity.getAmount()',
								orderId: 'entity.getSettle().getOrderItem().getOrder().getId()',
								orderNo: 'entity.getSettle().getOrderItem().getOrder().getNo()',
								user: 'entity.getSettle().getOrderItem().getOrder().getUser()'
							}
						}).then((res) => {
							console.log('orderItems',res.data)
							this.dateList[index].orderList = this.mergeItems(res.data)
							console.log(this.dateList[index].orderList)
							// this.dateList[index].show = true
							uni.hideLoading()
						})
					} else {
						// this.dateList[index].show = true
					}
				} else {
					uni.showToast({
						title: '无关联记录',
						icon: 'none'
					})
				}
			},
			// 合并相同的订单
			mergeItems(items) {
				const merged = {};
				items.forEach(item => {
					const key = `${item.orderId}-${item.orderNo}`;
					if (!merged[key]) {
						merged[key] = {
							...item
						}; // 复制当前项
					} else {
						// 如果键已经存在，则累加amount
						merged[key].amount = (parseFloat(merged[key].amount) + parseFloat(item.amount)).toFixed(2)
					}
				});

				// 将结果对象转换回数组
				return Object.values(merged);
			},
			// 按订单查分账明细
			getSettleDetail(id) {
				this.request.get(`api/settle-items`, {
					'@filter': `entity.getSettle().getOrderItem().getOrder().getId() == ${id}`,
					'@display': {
						amount: 'entity.getAmount()',
						profitType: 'entity.getProfitType()',
						specification: 'entity.getSettle().getOrderItem().getSpecification().getProduct().getName()',
						settled: 'entity.getSettled()'
					}
				}).then((res) => {
					console.log(res.data)
					this.orderSettleItems = res.data
					this.showItems = true
				})
			},
			toUrl(page){
				uni.navigateTo({
					url: page
				})
			}
		}
	}
</script>

<style>
	.condition {
		padding: 10px;
		background-color: #f3f3f3;
		position: fixed;
		width: 100%;
		top: 0px;
	}

	.type {
		background-color: #fff;
		border-radius: 20px;
		color: #606266;
		float: right;
		padding: 5px 20px;
		margin-right: 10px;
		font-size: 14px;
		line-height: 16px;
	}

	.title {
		color: #606266;
	}

	.time {
		color: #909399;
		font-size: 12px;
	}

	.list {
		padding: 5px;
		text-align: center;
		color:#909399;
	}

	.price {
		font-size: 21px;
		color: #f56c6c;
	}
	
	.order-list{
		border-radius: 5px;
		margin: 8px;
		border: solid #909399 1px;
	}
</style>